<?php
class APIManager {
    private static $instance = null;
    private $cache = [];
    private $cacheTime = 300; // 缓存时间，单位秒
    
    private function __construct() {
        // 私有构造函数，防止外部实例化
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function queryExpress($tracking_number, $carrier = '') {
        // 生成缓存键
        $cacheKey = md5($tracking_number . $carrier);
        
        // 检查缓存
        if (isset($this->cache[$cacheKey]) && 
            time() - $this->cache[$cacheKey]['time'] < $this->cacheTime) {
            return $this->cache[$cacheKey]['data'];
        }
        
        // 构建API URL
        $url = API_HOST . API_PATH . "?no=" . urlencode($tracking_number);
        if (!empty($carrier)) {
            $url .= "&type=" . urlencode($carrier);
        }
        
        $headers = array("Authorization:APPCODE " . API_APPCODE);
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        
        // 设置超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, 10); // 10秒超时
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); // 5秒连接超时
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        
        if ($httpCode == 200) {
            list($header, $body) = explode("\r\n\r\n", $response, 2);
            $result = json_decode($body, true);
            
            // 缓存结果
            $this->cache[$cacheKey] = [
                'time' => time(),
                'data' => $result
            ];
            
            return $result;
        } else {
            $error = curl_error($curl);
            curl_close($curl);
            throw new Exception("API请求失败: " . $error);
        }
    }
    
    // 清除缓存
    public function clearCache() {
        $this->cache = [];
    }
    
    // 设置缓存时间
    public function setCacheTime($seconds) {
        $this->cacheTime = $seconds;
    }
    
    // 防止克隆对象
    private function __clone() {}
    
    // 防止反序列化
    private function __wakeup() {}
} 